package com.zh.factorymode.demo;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public abstract class DBPool {
    public String propertiesName = "connection-INF.properties";

    private static DBPool instance = null;

    protected int maxConnect = 100;

    protected int normalConnect = 10;

    protected String driverName = null;

    protected Driver driver = null;

    protected DBPool() {
        try {

        }catch (Exception e){

        }
    }

    private void init() throws IOException{
        InputStream is = DBPool.class.getResourceAsStream(propertiesName);
        Properties p = new Properties();
        p.load(is);
        this.driverName = p.getProperty("driverName");
        this.maxConnect = Integer.parseInt(p.getProperty("maxConnect"));
        this.normalConnect = Integer.parseInt(p.getProperty("normalConnect"));
    }

    protected void loadDrivers(String dri) {
        String driverClassName = dri;
        try {
            driver = (Driver) Class.forName(driverClassName).newInstance();
            DriverManager.registerDriver(driver);
            System.out.println("成功注册JDBC驱动程序" + driverClassName);
        }catch (Exception e){
            System.out.println("无法注册JDBC驱动程序" + driverClassName + "，错误" + e);
        }
    }

    //创建连接池
    public abstract void createPool();

    /**
     * (单例模式)返回数据库连接池Pool的实例
     * @return
     * @throws IOException
     * @throws InstantiationException
     * @throws IllegalAccessException
     * @throws ClassNotFoundException
     */
    public static synchronized DBPool getInstance() throws IOException,InstantiationException, IllegalAccessException, ClassNotFoundException{
        if (instance == null) {
            instance.init();
            instance = (DBPool)Class.forName("org.e_book.sqlhelp.Pool").newInstance();
        }
        return instance;
    }

    // 获得一个可用的连接，如果没有则创建一个连接，且小于最大连接限制
    public abstract Connection getConnection();

    // 获得一个连接有时间限制
    public abstract Connection getConnection(long time);

    // 将连接对象返回给连接池
    public abstract void freeConnection(Connection con);

    //返回当前空闲连接数
    public abstract int getnum();

    // 返回当前工作的连接数
    public abstract int getnumActive();

    protected synchronized void release() {
        //撤销驱动
        try{
            DriverManager.deregisterDriver(driver);
            System.out.println("撤销JDBC驱动程序" + driver.getClass().getName());
        }catch (SQLException e){
            System.out.println("无法撤销JDBC驱动的注册：" + driver.getClass().getName() + "，错误：" + e);
        }
    }

}
